package yunquan.wang.base.spring.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import yunquan.wang.modules.base.entity.Authority;
import yunquan.wang.modules.base.service.AuthorityService;

public class SecurityMetadataSourceAuthImpl implements FilterInvocationSecurityMetadataSource{

	private Set<ConfigAttribute> authSet=new HashSet<ConfigAttribute>();
	private AuthorityService authorityService;
	  private  final AntPathMatcher antMatcher = new AntPathMatcher();
	public void setAuthorityService(AuthorityService authorityService) {
		this.authorityService = authorityService;
	}
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
        final HttpServletRequest request = ((FilterInvocation) object).getRequest();
		List<ConfigAttribute> configList=new ArrayList<ConfigAttribute>();
		for (ConfigAttribute config: authSet) {
			String authUrl="/"+config.getAttribute().replace("_", "/")+"*";
			if (antMatcher.match(authUrl.toLowerCase(), getRequestPath(request))) {
				configList.add(config);
			}
		}
		return configList;
	}
	private String getRequestPath(HttpServletRequest request) {
        String url = request.getServletPath();
        if (request.getPathInfo() != null) {
            url += request.getPathInfo();
        }
        url = url.toLowerCase();
        return url;
    }
	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		if(authSet.size()==0){
		List<Authority> authList = authorityService.findAll();
		for (Authority auth : authList) {
			authSet.add(new SecurityConfig(auth.getName()));
		}
		}
	return authSet;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
